package com.yami.shop.security.api.controller;

import cn.hutool.core.util.ObjectUtil;
import com.yami.shop.bean.app.param.WxLoginParam;
import com.yami.shop.bean.model.CarUser;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.util.PrincipalUtil;
import com.yami.shop.security.common.bo.CarUserInfoInTokenBO;
import com.yami.shop.security.common.bo.UserInfoInTokenBO;
import com.yami.shop.security.common.dto.AuthenticationDTO;
import com.yami.shop.security.common.enums.SysTypeEnum;
import com.yami.shop.security.common.manager.PasswordCheckManager;
import com.yami.shop.security.common.manager.PasswordManager;
import com.yami.shop.security.common.manager.TokenStore;
import com.yami.shop.security.common.vo.TokenInfoVO;
import com.yami.shop.service.CarUserService;
import com.yami.shop.service.WechatService;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import com.yami.shop.common.response.ServerResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import jakarta.validation.Valid;

/**
 * @author 菠萝凤梨
 * @date 2022/3/28 15:20
 */
@RestController
@Tag(name = "登录")
public class LoginController {
    @Autowired
    private TokenStore tokenStore;
    @Resource
    private CarUserService carUserService;

    @Resource
    private WechatService wechatService;

    @PostMapping("/wxLogin")
    @Operation(summary = "账号密码(用于前端登录)" , description = "通过账号/手机号/用户名密码登录，还要携带用户的类型，也就是用户所在的系统")
    public ServerResponseEntity<TokenInfoVO> wxLogin(
            @Valid @RequestBody WxLoginParam wxLoginParam) {

        String openId = wechatService.wxLogin(wxLoginParam.getJsCode());
        CarUser user = carUserService.getUserByOpenId(openId);
        Integer userId = null;
        if(ObjectUtil.isNull(user)){
            CarUser carUser = new CarUser();
            carUser.setOpenId(openId);
            carUser.setStatus(0);
            carUser.setSuperAdmin(0);
            carUserService.save(carUser);
            userId = carUser.getUserId();
        }else{
            userId = user.getUserId();
        }

        CarUserInfoInTokenBO carUserInfoInTokenBO = new CarUserInfoInTokenBO();
        carUserInfoInTokenBO.setUserId(userId);
        carUserInfoInTokenBO.setSysType(SysTypeEnum.ORDINARY.value());

        // 存储token返回vo
        TokenInfoVO tokenInfoVO = tokenStore.carUserLogin(carUserInfoInTokenBO);
        return ServerResponseEntity.success(tokenInfoVO);
    }
}
